//
//  YHIolInfoListView.m
//  ZhuKuang
//
//  Created by jjkj on 17/7/12.
//  Copyright © 2017年 jjkj. All rights reserved.
//

#import "YHIolInfoListView.h"
#import "YHIolInfoListCell.h"
#import "YHIolAlarmSubCell.h"
#import "YHIolInfoListModel.h"
#import "ErrorModel.h"
#import "YHTimeSingleModel.h"
#import "YHTimeSubView.h"
#import "IolDetailModel.h"
@interface YHIolInfoListView()<UITableViewDelegate,UITableViewDataSource>

{
    /**分页页码*/
    NSInteger _pageNum;
}

/**标题*/
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
/** 报警车辆／异常车辆／发油单位 标题*/
@property (weak, nonatomic) IBOutlet UILabel *carTitleLabel;
/** 油耗异常量／入油异常量／出油异常量／报警类型／超速速度／加油异常量 标题*/
@property (weak, nonatomic) IBOutlet UILabel *iolNumTitleLabel;
/**报警时间 标题*/
@property (weak, nonatomic) IBOutlet UILabel *timeTitleLabel;
/**列表*/
@property (weak, nonatomic) IBOutlet UITableView *iolTableView;
@property (nonatomic, strong) MJRefreshFooter *refreshFooterView;

@property (nonatomic, strong) YHTimeSubView * subDetailView;

@end
@implementation YHIolInfoListView

-(void)awakeFromNib
{
    [super awakeFromNib];
    self.layer.borderColor = [UIColor colorWithHexString:@"#1590CC"].CGColor;
    [self.iolTableView registerNib:[UINib nibWithNibName:YHIolInfoListCellIdentifier bundle:nil] forCellReuseIdentifier:NSStringFromClass([YHIolInfoListCell class])];
    [self.iolTableView registerNib:[UINib nibWithNibName:YHIolAlarmSubCellIdentifier bundle:nil] forCellReuseIdentifier:NSStringFromClass([YHIolAlarmSubCell class])];
    self.iolTableView.tableFooterView = [[UIView alloc]init];
     __weak typeof(self) weakSelf = self;
    self.refreshFooterView = [CommClass setUpFooterRefresh:self.iolTableView withBlock:^{
        [weakSelf footerRereshing];
    }];
}
#pragma mark - 懒加载
-(YHTimeSubView *)subDetailView
{
    if (!_subDetailView) {
        _subDetailView = [YHTimeSubView viewFromXib];
    }
    return _subDetailView;
}
-(NSMutableArray *)iolInfoList
{
    if (!_iolInfoList) {
        _iolInfoList = [[NSMutableArray alloc]init];
    }
    return _iolInfoList;
}
/**上拉加载*/
-(void)footerRereshing{
    _pageNum ++;
    [self getCarAlarm];
}

#pragma mark - interface
-(void)getCarAlarm
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, globalNum0), ^{
        [ClientRequest SOAPMthod:getTypeErrorList
                        soapBody:@{@"starttime":self.startTime?self.startTime:@"2017-06-03",
                                   @"endtime":self.endTime?self.endTime:@"2017-07-12",
                                   @"type":@(self.type),
                                   @"page":@(_pageNum),
                                   @"carShopId":self.carShopId?self.carShopId:@""}
                         success:^(id responseObject) {
                            [MBProgressHUD hideLoadViewWithView:kWindow];
                             [self.refreshFooterView endRefreshing];
                             if ([DataCheck isValidDictionary:responseObject]) {
                                 if (_pageNum == globalNum0) {
                                     self.iolInfoList = [YHIolInfoListModel mj_objectArrayWithKeyValuesArray:responseObject[@"errorList"]];
                                 }else{
                                    [self.iolInfoList addObjectsFromArray:[YHIolInfoListModel mj_objectArrayWithKeyValuesArray:responseObject[@"errorList"]]];
                                 }
                                 dispatch_async(dispatch_get_main_queue(), ^{
                                     [self.iolTableView reloadData];
                                 });
                             }else{
                                 _pageNum--;
                             }
                         } failure:^(NSError *error) {
                             dispatch_async(dispatch_get_main_queue(), ^{
                                 [MBProgressHUD hideLoadViewWithView:kWindow];
                                 _pageNum--;
                                 [self.refreshFooterView endRefreshing];
                             });
                         }];

    });
}

#pragma mark - table delegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.iolInfoList.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ([DataCheck isValidArray:self.iolInfoList] && !self.isCar) {
        ErrorModel * model = self.iolInfoList[section];
        if (self.type == globalNum0) {
            return model.singleInList.count+globalNum1;
        }
        return model.singleoutList.count+globalNum1;
    }
    return globalNum1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row > globalNum0) {
        ErrorModel * model = self.iolInfoList[indexPath.section];
        NSArray * sublist;
        if (self.type == globalNum0) {
            //入油
            sublist = model.singleInList;
        }else{
            //出油
            sublist = model.singleoutList;
        }
        return indexPath.row==sublist.count?(YHIolInfoSingleCellHeight+10):YHIolInfoSingleCellHeight;;
    }
    return YHIolInfoCellHeight;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == globalNum0) {
        //车辆报警和油耗业务报警的第一行
        YHIolInfoListCell * cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([YHIolInfoListCell class])];
        cell.type = self.type;
        if (self.isCar) {
            //车辆报警
            cell.carAlarmIolModel = self.iolInfoList[indexPath.section];
        }else{
           //油耗报警
            cell.iolErrorModel = self.iolInfoList[indexPath.section];
        }
        return cell;
    }else{
        YHIolAlarmSubCell * cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([YHIolAlarmSubCell class])];
        ErrorModel * model = self.iolInfoList[indexPath.section];
        cell.section = indexPath.section;
        NSArray * sublist;
        if (self.type == globalNum0) {
            //入油
            sublist = model.singleInList;
        }else{
            //出油
            sublist = model.singleoutList;
        }
        cell.singleModel = sublist[indexPath.row-1];
        cell.isLast = indexPath.row==sublist.count?YES:NO;
        __weak typeof(self) weakSelf = self;
        cell.singleClickBlock = ^(){
            [weakSelf showSingleView:nil withSubModel:sublist[indexPath.row-1]];
        };
        return cell;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.isCar) {
       [self showSingleView:self.iolInfoList[indexPath.section] withSubModel:nil];
    }
}
#pragma mark - 显示、隐藏
/**显示*/
-(void)show
{
    [self setTableViewHeader];
    if (self.isCar) {
         self.iolTableView.allowsSelection = YES;
        [MBProgressHUD postLoadViewWithText:HUD_PLEASEWAIT View:kWindow];
        [self getCarAlarm];
    }else{
        self.iolTableView.allowsSelection = NO;
        [self.iolTableView reloadData];
    }
    [kWindow addSubview:self.maskView];
//    [kWindow addSubview:self];
    [UIView animateWithDuration:0.5 animations:^{
        self.transform = CGAffineTransformTranslate(self.transform, globalNum0, -YHIolInfoViewHeight);
        self.height = YHIolInfoViewHeight;
    }];
    
}
/**隐藏*/
-(void)hidden
{
    [self.maskView removeFromSuperview];
    [UIView animateWithDuration:0.5 animations:^{
        self.transform = CGAffineTransformTranslate(self.transform, globalNum0, YHIolInfoViewHeight);
        self.height = globalNum0;
        _pageNum = globalNum0;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}
/**是否显示*/
-(BOOL)isShow
{
    return self.height > globalNum0?YES:NO;
}
#pragma mark - 背景
-(UIView *)maskView
{
    if (!_maskView) {
        _maskView = [[UIView alloc]init];
        _maskView.frame = kWindow.bounds;
        _maskView.height = self.y-YHIolInfoViewHeight;
        _maskView.backgroundColor = [UIColor clearColor];
        _maskView.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hidden)];
        [_maskView addGestureRecognizer:tap];
    }
    return _maskView;
}

#pragma mark - 设置标题
/**
 设置列表表头标题和页面标题
 */
-(void)setTableViewHeader
{
    if (self.isCar) {
        //车辆报警
        self.carTitleLabel.text = @"报警车辆";
        switch (self.type) {
            case 0:
                self.titleLabel.text = @"车辆油耗报警记录";
                self.iolNumTitleLabel.text = @"油耗异常量";
                break;
            case 2:
                self.titleLabel.text = @"车辆故障报警记录";
                self.iolNumTitleLabel.text = @"报警类型";
                break;
            case 3:
                self.titleLabel.text = @"车辆超速报警记录";
                self.iolNumTitleLabel.text = @"超速速度";
                break;
            case 4:
                self.titleLabel.text = @"车辆加油报警记录";
                self.iolNumTitleLabel.text = @"加油异常量";
                break;
            default:
                break;
        }
    }else{
       //加油、入油
        if (self.type == globalNum1) {
            //出油
            self.carTitleLabel.text = @"异常车辆";
            self.titleLabel.text = @"出油报警记录";
            self.iolNumTitleLabel.text = @"出油异常量";
        }else{
           //入油
            self.carTitleLabel.text = @"发油单位";
            self.titleLabel.text = @"入油报警记录";
            self.iolNumTitleLabel.text = @"入油异常量";
        }
    }
}

#pragma mark - 报警详情
/**
 * 油耗业务弹出报警详情
 * model 数据
 */

-(void)showSingleView:(YHIolInfoListModel *)model withSubModel:(YHTimeSingleModel *)subModel
{
    
    
    if (model) {
        self.subDetailView.singleTime = model.errortime;
        self.subDetailView.carId = model.carid;
        self.subDetailView.bussinessId = model.BusinessID;
        NSString * title;
        switch (self.type) {
            case 0:
                title = @"油耗异常";
                break;
            case 2:
                title = @"故障异常";
                break;
            case 3:
                title = @"超速";
                break;
            case 4:
                title = @"车辆加油异常";
                break;
            default:
                break;
        }
        if (self.type == 4) {
            [self.subDetailView setType:YES withData:[IolDetailModel getCarRefuelIolAlarmDetail:model] withTitle:title withIolType:NO];
        }else{
            [self.subDetailView setType:YES withData:[IolDetailModel getCarAlarmDetail:model withType:self.type] withTitle:title withIolType:NO];
        }
        __weak typeof(self) weakSelf = self;
        self.subDetailView.maskBlock = ^(){
            weakSelf.maskView.hidden = YES;
        };
    }else{
        NSString * title = [subModel.iolnum stringByAppendingString:@"入油异常"];
        if (self.type == globalNum1) {
            title = [subModel.iolnum stringByAppendingString:@"出油异常"];
        }
        [self.subDetailView setType:YES withData:[IolDetailModel getSingleIolDetail:subModel withType:title] withTitle:title withIolType:YES];
    }
}


@end
